
const ws = require("nodejs-websocket");
console.log("开始建立连接...");

var game1=game2=null;
var game1Ready = game2Ready = false;

//conn 每达成一次请求生成一个新的对象，所以game1 和 game2 是不一样的 
var server = ws.createServer(function(conn){
    console.log("这里可以知道建立server 的过程是不是同步阻塞的");

    conn.on("text", function(str){
        console.log("收到的信息为："+str);
        if(str==="game1"){
            game1 = conn;
            game1Ready = true;
        }else if(str=="game2"){
            game2 = conn;
            game2Ready = true;
        }

        console.log("game1===game2:");
        console.log(game1===game2);

        //两个都连接成功才算成功
        if(game1Ready && game2Ready){
            if(str=="game1" || str=="game2"){
                game1.sendText("success");
                game2.sendText("success");
            }else{
                //不能区分请求来自于谁吗？
                game1.sendText(str);
                game2.sendText(str);
            }
        }
    })

    conn.on("close",function(code, reason){
        console.log("关闭连接");
        console.log("code:")
        console.log(code);
        console.log("reason");
        console.log(reason);
    })

    conn.on("error",function(code, reason){
        console.log("错误导致连接关闭");
        console.log("code:")
        console.log(code);
        console.log("reason");
        console.log(reason);
    })
}).listen(8001);
console.log("websocket连接建立完毕");